Repository navigation
feat(schema): unify pydantic model, mirror permissions in ActionSchema, add side_effect - #293
Conversation
…a, add side_effect Three related gaps closed: 1. @Schema built its own pydantic Model via create_model(), then separately handed the raw input dict to validate_payload() which built ANOTHER model from scratch. Now @Schema builds the Model once and passes it directly to validate_payload(schema=Model, ...). That same Model's model_json_schema() is stored as input_json_schema/output_json_schema on ActionSchema — a real JSON Schema (nested fields, defaults, constraints), not just the existing flat {field: type_name} dict (kept as-is, still what BreakingChangeDetector compares). 2. permissions/permission_groups lived only on the function (_xcore_action_permissions/_xcore_action_permission_groups), readable only via a live LifecycleManager.get_action_permissions()/ get_action_permission_groups() per plugin instance. Mirrored them onto ActionSchema too, and widened _register_schemas() to register an entry for every @action (not only those with @Schema also stacked) — otherwise an action with only permissions and no schema silently never reached schema_registry at all. External tooling can now read schema AND permissions for the whole system from schema_registry alone. 3. permissions answers "who can call this", not "how consequential is it once authorized" — a legitimate caller can still trigger something irreversible. @action(side_effect="read"|"write"|"outbound") declares that as an orthogonal, purely informational axis (also mirrored on ActionSchema): the kernel enforces nothing on it itself, it's for an external consumer (e.g. a bridge exposing actions as LLM tools) to decide whether an action can be a direct tool or needs approval first. Invalid values raise ValueError at decoration time.
Reviewer's GuideThe PR unifies Pydantic model construction for validation and rich JSON Schema generation, expands ActionSchema and registration into a complete metadata catalog for all actions, adds declarative side-effect classification, and documents the resulting authorization and external-tooling semantics. Sequence diagram for action metadata registrationsequenceDiagram
participant Plugin as PluginMixin
participant Method as DecoratedAction
participant Registry as SchemaRegistry
participant Catalog as ExternalConsumer
Plugin->>Plugin: _register_schemas(plugin_name)
Plugin->>Method: Read _xcore_action and metadata
Method-->>Plugin: action, schema, permissions, side_effect
Plugin->>Registry: register(ActionSchema)
Registry-->>Catalog: Complete action catalog
Catalog->>Registry: Read schema and authorization metadata
Sequence diagram for unified schema model validationsequenceDiagram
participant Decorator as schema
participant Model as PydanticModel
participant Validator as validate_payload
participant Action as ActionHandler
participant Consumer as SchemaConsumer
Decorator->>Model: create_model(input)
Decorator->>Validator: validate_payload(schema=Model)
Decorator->>Model: model_json_schema()
Model-->>Decorator: input_json_schema
Decorator->>Action: Store schema metadata
Consumer->>Action: Read input_json_schema
Flow diagram for authorization and side-effect classificationflowchart LR
Action["@action metadata"] --> Auth["Authorization requirements"]
Auth --> Permissions["permissions: AND"]
Auth --> Groups["permission_groups: OR of AND"]
Permissions --> Authorized["Authorized call"]
Groups --> Authorized
Authorized --> Risk["side_effect classification"]
Risk --> Consumer["External consumer decides approval"]
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey - I've found 3 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="xcore/sdk/decorators.py" line_range="131-133" />
<code_context>
"deprecated_fields": deprecated_fields or {},
"breaking_since": breaking_since,
"description": description,
+ "input_json_schema": InputModel.model_json_schema() if InputModel else {},
+ "output_json_schema": (
+ OutputModel.model_json_schema() if OutputModel else {}
+ ),
}
</code_context>
<issue_to_address>
**Actions fail during import**
When an input or output field has a Pydantic-supported type without a JSON Schema representation, such as `Callable`, `model_json_schema()` raises while the decorator builds schema metadata, so the action fails to load even when validation is disabled or the output model is metadata-only.
Make JSON Schema generation non-fatal for types without a JSON Schema representation.
</issue_to_address>
### Comment 2
<location path="xcore/kernel/schema/registry.py" line_range="43-44" />
<code_context>
+ # BreakingChangeDetector (comparaison type-par-type) ; ces deux champs sont
+ # pour les consommateurs externes (génération de tools LLM, OpenAPI, etc.)
+ # qui ont besoin de la forme complète, pas juste du nom du type.
+ input_json_schema: dict[str, Any] = field(default_factory=dict)
+ output_json_schema: dict[str, Any] = field(default_factory=dict)
+ # Miroir de fn._xcore_action_permissions / _xcore_action_permission_groups
+ # (@action(permissions=..., permission_groups=...), voir sdk/decorators.py).
</code_context>
<issue_to_address>
**Older readers discard schema snapshots**
When an older CLI or runtime loads a snapshot written by this version, `ActionSchema.to_dict()` persists the added fields, but older strict `ActionSchema` constructors reject them and `SchemaRegistry.load()` skips the entries. Rollbacks then lose the schemas used for breaking-change comparisons.
Make loading tolerate unknown fields or version and migrate the snapshot format.
</issue_to_address>
### Comment 3
<location path="xcore/sdk/decorators.py" line_range="193-197" />
<code_context>
async def create_user(self, payload: dict) -> dict:
...
"""
+ if side_effect is not None and side_effect not in _VALID_SIDE_EFFECTS:
+ raise ValueError(
+ f"side_effect invalide : {side_effect!r} — attendu l'un de "
+ f"{sorted(_VALID_SIDE_EFFECTS)} ou None"
+ )
def decorator(fn: Callable) -> Callable:
</code_context>
<issue_to_address>
**Invalid values raise wrong exception**
When a caller passes an unhashable invalid `side_effect`, such as a list or dict, the membership check against `_VALID_SIDE_EFFECTS` hashes the value and raises `TypeError` instead of the documented `ValueError` at decoration time.
Validate the value without hashing unhashable inputs, and raise `ValueError` for invalid values.
</issue_to_address>Sourcery assessment
Approval pending. 2 findings to address first.
Blocking findings: xcore/sdk/decorators.py:133, xcore/kernel/schema/registry.py:44
| "input_json_schema": InputModel.model_json_schema() if InputModel else {}, | ||
| "output_json_schema": ( | ||
| OutputModel.model_json_schema() if OutputModel else {} |
There was a problem hiding this comment.
🟠 High · Actions fail during import
When an input or output field has a Pydantic-supported type without a JSON Schema representation, such as Callable, model_json_schema() raises while the decorator builds schema metadata, so the action fails to load even when validation is disabled or the output model is metadata-only.
Make JSON Schema generation non-fatal for types without a JSON Schema representation.
Prompt for AI agents
In `xcore/sdk/decorators.py` at lines 131-133:
**Actions fail during import**
When an input or output field has a Pydantic-supported type without a JSON Schema representation, such as `Callable`, `model_json_schema()` raises while the decorator builds schema metadata, so the action fails to load even when validation is disabled or the output model is metadata-only.
Make JSON Schema generation non-fatal for types without a JSON Schema representation.| input_json_schema: dict[str, Any] = field(default_factory=dict) | ||
| output_json_schema: dict[str, Any] = field(default_factory=dict) |
There was a problem hiding this comment.
🟡 Medium · Older readers discard schema snapshots
When an older CLI or runtime loads a snapshot written by this version, ActionSchema.to_dict() persists the added fields, but older strict ActionSchema constructors reject them and SchemaRegistry.load() skips the entries. Rollbacks then lose the schemas used for breaking-change comparisons.
Make loading tolerate unknown fields or version and migrate the snapshot format.
Prompt for AI agents
In `xcore/kernel/schema/registry.py` at lines 43-44:
**Older readers discard schema snapshots**
When an older CLI or runtime loads a snapshot written by this version, `ActionSchema.to_dict()` persists the added fields, but older strict `ActionSchema` constructors reject them and `SchemaRegistry.load()` skips the entries. Rollbacks then lose the schemas used for breaking-change comparisons.
Make loading tolerate unknown fields or version and migrate the snapshot format.| if side_effect is not None and side_effect not in _VALID_SIDE_EFFECTS: | ||
| raise ValueError( | ||
| f"side_effect invalide : {side_effect!r} — attendu l'un de " | ||
| f"{sorted(_VALID_SIDE_EFFECTS)} ou None" | ||
| ) |
There was a problem hiding this comment.
⚪ Low · Invalid values raise wrong exception
When a caller passes an unhashable invalid side_effect, such as a list or dict, the membership check against _VALID_SIDE_EFFECTS hashes the value and raises TypeError instead of the documented ValueError at decoration time.
Validate the value without hashing unhashable inputs, and raise ValueError for invalid values.
Prompt for AI agents
In `xcore/sdk/decorators.py` at lines 193-197:
**Invalid values raise wrong exception**
When a caller passes an unhashable invalid `side_effect`, such as a list or dict, the membership check against `_VALID_SIDE_EFFECTS` hashes the value and raises `TypeError` instead of the documented `ValueError` at decoration time.
Validate the value without hashing unhashable inputs, and raise `ValueError` for invalid values.## Summary - CHANGELOG entry for `permission_groups`, `side_effect`, and the `ActionSchema`/registry work from #292 and #293. - Version bump to 2.9.0: `pyproject.toml`, `xcore/__version__.py` (also fixes `__version_info__`, which had drifted to `(2, 7, 1)` since the 2.8.1 bump — left stale by that release), `CLAUDE.md`. - `CLAUDE.md`'s HTTP call-flow diagram and `doc/advanced/middleware.md`'s Action Permissions section now mention `permission_groups`, not just `permissions`. ## Test plan - [x] `poetry run pytest tests/unit tests/integration -q` — 1415 passed, 1 pre-existing unrelated skip - [x] `poetry run mkdocs build --strict` — clean (pre-existing unrelated warnings only) - [x] version consistent across all three files - [x] pre-commit hooks passed on the commit ## Summary by Sourcery Release version 2.9.0 with updated version metadata, changelog coverage, and documentation for the new action authorization and schema capabilities. Bug Fixes: - Correct the stale `__version_info__` value so it matches the released version. Enhancements: - Document action permission groups and their authorization behavior. - Document the updated HTTP middleware flow and the distinction between action permissions and plugin ACL permissions. Build: - Bump the project version to 2.9.0 across package metadata and runtime version information. Documentation: - Add the 2.9.0 changelog covering permission groups, side-effect metadata, enriched action schemas, and schema registration changes.
Summary
@schemanow builds the pydanticModelonce and passes it directly tovalidate_payload(schema=Model, ...)instead of each rebuilding their own from the sameinputdict. That sameModel.model_json_schema()is stored asinput_json_schema/output_json_schemaonActionSchema— a real JSON Schema (nested fields, defaults, constraints), not just the existing flat{field: type_name}dict (kept as-is, still whatBreakingChangeDetectorcompares).permissions/permission_groupswere only readable via a liveLifecycleManagerper plugin instance. Mirrored them ontoActionSchema, and widened_register_schemas()to register an entry for every@action(not only those with@schemaalso stacked) — otherwise an action with only permissions and no schema silently never reachedschema_registryat all. External tooling can now read schema + permissions for the whole system fromschema_registryalone.permissionsanswers "who can call this", not "how consequential is it once authorized".@action(side_effect="read"|"write"|"outbound")declares that as an orthogonal, purely informational axis (also mirrored onActionSchema) — the kernel enforces nothing on it, it's for an external consumer (e.g. a bridge exposing actions as LLM tools) to decide whether an action needs approval first. Invalid values raiseValueErrorat decoration time.Test plan
poetry run pytest tests/unit tests/integration -q— 1415 passed, 1 pre-existing unrelated skippoetry run mkdocs build --strict— clean (pre-existing unrelated warnings only)make lint-check— passedSummary by Sourcery
Unify action schema generation and expand the action registry with authorization and side-effect metadata for external consumers.
New Features:
Bug Fixes:
Enhancements:
Documentation:
Tests: